package leechapi.main;

import static leechapi.main.Log.*;

import java.sql.PreparedStatement;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.Bullet;
import org.htmlparser.tags.InputTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;

/**
 * Instanciation pour OF
 */
public class OFLeecher extends AbstractLeecher {
	
	private String ville;

	public OFLeecher(String url, String description, String ville,ProcessingContext pc) {
		super(url, description, pc);
		this.ville = ville;
	}

	@Override
	protected ParsableInput buildNextParsableInput() {
		int numPage = getPc().getNumPage().getAndIncrement();
		String lieuToken = ville+'-'+getDescription().substring(0,2)+'-'+getDescription();
		String result = getUrl().replace("LIEU", lieuToken);
		result = result.replace("page=1", "page="+numPage);
		log(Thread.currentThread().getName() + " : Traitement de la page " + numPage + " de " + ville);
		ParsableInput toBeReturned = new ParsableInput();
		toBeReturned.setParsableUrl(result);
		return toBeReturned;
	}

	@Override
	protected boolean extractDataFromParser(Parser p, PreparedStatement ppInsert) throws Exception {
		boolean returnResult = false;
		NodeList result = p.parse(null);
		NodeList filtered = result.extractAllNodesThatMatch(new AndFilter(new NodeFilter[] { new HasAttributeFilter("id", "colCentreListe"), new TagNameFilter("div") }), true);
		if (filtered.size() != 0) {
				NodeList ul = filtered.elementAt(0).getChildren().extractAllNodesThatMatch(new AndFilter(new NodeFilter[] { new HasAttributeFilter("class", "listeAnn"), new TagNameFilter("ul") }), true);
				if (ul != null && ul.size() > 0) {
					NodeList lis = ul.elementAt(0).getChildren().extractAllNodesThatMatch(new TagNameFilter("li"), true);
					if (lis != null && lis.size() > 0) {
						for (int k=0;k<lis.size();k++) {
							Bullet li = (Bullet) lis.elementAt(k);
							String classValue = li.getAttribute("class");
							if (classValue != null && classValue.equals("polePosition")) {
								continue;
							}
							NodeList as = li.getChildren().extractAllNodesThatMatch(new AndFilter(new NodeFilter[] { new HasAttributeFilter("class", "prix lienDetail"), new TagNameFilter("a") }), true);
							if (as != null && as.size() > 0) {
								LinkTag lien = (LinkTag)as.elementAt(0);
								String urlFiche = lien.getLink();
								Parser pFiche = null;
								int nbEssais = 0;
								while (nbEssais <= 3) {
									try {
										pFiche = new Parser(urlFiche);
										nbEssais++;
									} catch (Exception e) {
										e.printStackTrace();
										Thread.sleep(5000);
									}
								}
								NodeList resultFiche = pFiche.parse(null);
								String annId = urlFiche.substring(urlFiche.lastIndexOf('/')+1,urlFiche.lastIndexOf('.'));
								ppInsert.setString(1, annId);
								NodeList lienPrix = resultFiche.extractAllNodesThatMatch(new AndFilter(new NodeFilter[] { new HasAttributeFilter("id", "prix_cliquable"), new TagNameFilter("a") }), true);
								int vraiprix = -1;
								try {
									LinkTag linkPrix = (LinkTag)lienPrix.elementAt(0);
									String textPrix = linkPrix.getChildrenHTML();
									textPrix = textPrix.replaceAll( "[^\\d]", "" );
									vraiprix = Integer.parseInt(textPrix);
								} catch (Exception nfe) {
								}
								ppInsert.setInt(2, vraiprix);
								java.sql.Date dateOperation = new java.sql.Date(getPc().getDate().getTime());
								ppInsert.setDate(3, dateOperation);
								ppInsert.setString(4, urlFiche);
								ppInsert.setString(5, getDescription());
								ppInsert.setInt(6, Site.OUEST_FRANCE_ID);
								ppInsert.executeUpdate();
								returnResult = true;
							}
						}
				}
			}
			Thread.sleep(1000);
		}
		return returnResult;
	}

}
